package com.lzp.gateway;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {
    public AgeRoutePredicateFactory() {
        super(Config.class);
    }
    //1. 进行断言条件判断比较
    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            //1.1 得到当前的请求对象
            ServerHttpRequest request = exchange.getRequest();
            //1.2 得到参数的值
            String ageStr = request.getQueryParams().getFirst("age");
            //1.3 转换年龄
            if(StrUtil.isNotBlank(ageStr)){
                int age = Integer.parseInt(ageStr);
                return age >= config.getMinAge() && age <= config.getMaxAge();
            }
            return false;
        };
    }

    //2. 定义参数的名字的顺序
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge","maxAge");        // age: 10,20
    }
    //3. 定义参数的名字，并且设置对应的setter与getter方法
    @Data
    public static class Config {
        private int minAge;
        private int maxAge;
    }
}
